package com.example.gfsquadwebviewproject.presenter.http.post;

import org.apache.http.NameValuePair;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/1/2 0002.
 */

public  class OkhttpPost implements IPost {

    IPostRequest iPostRequest;

    public OkhttpPost(IPostRequest iPostRequest){
        this.iPostRequest = iPostRequest;
    }

    @Override
    public void post(final String url, final int methodType, final int requestCount, List<NameValuePair> header,
                     final List<NameValuePair> body){
        try {

            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .build();

            FormBody.Builder bodyBuilder = new FormBody.Builder();
            if (body != null && body.size() > 0) {
                for (int i = 0; i < body.size(); i++) {
                    bodyBuilder.add(body.get(i).getName(), body.get(i).getValue());
                }
            }
            RequestBody formBody = bodyBuilder.build();
            Request.Builder requestBuilder = new Request.Builder().url(url).post(formBody);

            if (header != null && header.size() > 0) {
                for (int i = 0; i < header.size(); i++) {
                    requestBuilder.addHeader(header.get(i).getName(), header.get(i).getValue());
                }
            }
            Request request = requestBuilder.build();

            Call call = okHttpClient.newCall(request);

            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //请求失败的处理
                    iPostRequest.requestBackMsg(e.getMessage(), methodType, 0,body);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    iPostRequest.requestBackMsg(response.body().string(), methodType, 1,body);
                }
            });
        }
        catch (Exception e){
            //请求失败的处理
            iPostRequest.requestBackMsg(e.getMessage(), methodType, 0,body);
        }

    }

}
